package thread;

import java.util.concurrent.TimeUnit;

public class DaemonTest {
	public static void main(String[] args) throws InterruptedException {
		Thread t1 = new MyThread();
		Thread t3 = new MyThread2();
		Thread t2 = new MyDaemon();
		//设置为守护线程
		t2.setDaemon(true);
		t1.start();
		t2.start();
		t3.start();
		int i = 1;
		//main 线程没有结束，守护线程也不会提前结束
		//如果守护线程自己先执行完毕了，就没有机会等到所有线程全结束再结束
		while(i<=15){
			System.out.println("this is main thread:"+i++);
			TimeUnit.SECONDS.sleep(1);
		}
		System.out.println("t2 is alive:"+t2.isAlive());//如果守护线程没有执行完毕，则为true
		System.out.println("main thread over");
		System.out.println("t2 is alive:"+t2.isAlive());//如果守护线程没有执行完毕，则为true
	}
}

class MyDaemon extends Thread {
	@Override
	public void run() {
		for(int i=1;i<=20;i++){
			try {
				TimeUnit.SECONDS.sleep(1);
				System.out.println("this is daemon thread:"+i);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

class MyThread extends Thread {
	@Override
	public void run() {
		for(int i=1;i<=5;i++){
			try {
				//线程睡眠
				TimeUnit.SECONDS.sleep(1);
				System.out.println("this is my thread:"+i);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("MyThread over");
	}
}

class MyThread2 extends Thread {
	@Override
	public void run() {
		for(int i=1;i<=10;i++){
			try {
				//线程睡眠
				TimeUnit.SECONDS.sleep(1);
				System.out.println("this is my thread2:"+i);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("MyThread2 over");
	}
}